import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Select, Calendar, Typography, Badge,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

let UUID = require('uuid-js');
import sortBy from 'lodash/sortBy';
import min from 'lodash/min';
import max from 'lodash/max';
import ReactEcharts from 'echarts-for-react';
import styles from './index.less';
import debounce from 'lodash/debounce';
import {ellipsis, afterCloseModal, DescriptionItem} from '@/utils/utils';
import {
  sortableContainer,
  sortableElement,
  sortableHandle,
} from 'react-sortable-hoc';
import arrayMove from 'array-move';
import Polyfit from './polyfit.js'
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditPrice from './AddOrEditPrice';
import menu from './../../images/menu.png';
import plus from './../../images/plus.png';
import find from "lodash/find";

const FormItem = Form.Item;
const {confirm} = Modal;
const {Option} = Select;
const RadioButton = Radio.Button;
const {Text} = Typography;
const RadioGroup = Radio.Group;

@connect(({tools, loading, global}) => ({
  tools,
  global,
  loading: loading.models.tools,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      meter9: [],
      meter10: [],

    };
  }

  clearTable = () => {
    let {
      dispatch, tools
    } = this.props;
    let pressureOrPosition = {}
    for (let key in tools) {
      if (key.indexOf('pressure') >= 0 || key.indexOf('position') >= 0) {
        pressureOrPosition[key] = ''
      }
    }
    console.log('tools', tools)
    dispatch({
      type: 'tools/changeTable',
      payload: {
        uuid: 10,
        meterArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
        meter1: [],
        meter2: [],
        meter3: [],
        meter4: [],
        meter5: [],
        meter6: [],
        meter7: [],
        meter8: [],
        meter9: [],
        meter10: [],
        terms:[],//多项式系数
        trendY:[],//趋势线
        cc:'',
        r:'',
        p0:'',
        p1:'',
        p2:'',
        p3:'',
        x:[],
        y:[],
        ...pressureOrPosition
      },
    });
    this.props.form.resetFields();
  };
  complete = () => {
    let {
      dispatch, tools
    } = this.props;
    let pressure = []
    let position = []
    for (let key in tools) {
      if (key.indexOf('pressure') >= 0) {
        if (tools[key] !== '') {
          pressure.push(Number(tools[key])*1000)
        }
      }
    }
    for (let key in tools) {
      if (key.indexOf('position') >= 0) {
        if (tools[key] !== '') {
          position.push(Number(tools[key]))
        }

      }
    }
    console.log('pressure', pressure)
    console.log('position', position)
    console.log('degree', tools.degree)
    if (pressure.length === 0 || position.length === 0) {
      message.error('至少需要一组值')
      return false
    }
    if (pressure.length !== position.length) {
      message.error('压力和位置个数不同')
      return false
    }
    let pressArr=[];
    for(let i=0;i<pressure.length;i++){
      pressArr.push({
        pressure:pressure[i],
        position:position[i],
      })
    }
    let pressSortArr=sortBy(pressArr,'pressure')
    console.log('pressSortArr',pressSortArr)
    // 将数据点转换为 x 和 y 数组
    const x =pressSortArr.map(function (item){
      return item.pressure
    }); // 对应压力(Kpa),界面输入Mpa
    const y = pressSortArr.map(function (item){
      return item.position
    }) // 对应位置
    console.log('x',x)
    console.log('y',y)
    var poly = new Polyfit(x, y);
    var terms = poly.computeCoefficients(tools.degree); /* 参数[3]为阶数，返回terms为系数列表，对应为P0~Px(阶数为3时，x为3； 阶数为3时，x为2) */
    for (let index = 0; index < terms.length; index++) {
      terms[index] = Number(terms[index].toFixed(6));
    }

    var solver = poly.getPolynomial2(tools.degree, terms);  /* 参数[3]为阶数 */
    var cc = poly.correlationCoefficient(terms);
    var r = poly.standardError(terms);

    // 输出拟合结果
    console.log(`多项式系数：${terms}`);
    //6320,31.033333,-0.083,0.000087
    // 从拟合结果，得出趋势线的Y坐标
    let trendY=[]
    for (let index = 0; index < x.length; index++) {
      console.log(`[${index}]: ${solver(x[index])}`);//趋势线
      trendY.push(solver(x[index]))
      /*
        [0]: 9902.6666
        [1]: 10508.999899999999
        [2]: 10744.291550000002
        [3]: 11021.333200000001
        */
    }
    console.log(`cc: ${cc}`);
    console.log(`r: ${r}`)
    /*
    * cc: 0.9999842536579293
      r: 19.332133602018327
      *
     */
    dispatch({
      type: 'tools/changeTable',
      payload: {
        terms, trendY, cc,r,x,y
      },
    });
  }
  addMeter = () => {
    let {
      dispatch, tools: {meterArr, meterActiveKey, uuid},
    } = this.props;
    uuid = uuid + 1;
    meterArr.push(uuid);
    meterActiveKey.push(uuid.toString());
    dispatch({
      type: 'tools/changeTable',
      payload: {
        uuid, meterArr, meterActiveKey
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    let {
      dispatch, tools: {meterArr, meterActiveKey, uuid},
    } = this.props;
    if (meterArr.length === 1) {
      console.log('只有一个水表');
      message.error('至少需要一项')
      return false
    }
    const index = meterArr.indexOf(item);
    console.log('index', index);
    meterArr.splice(index, 1);
    meterActiveKey.splice(index, 1);
    dispatch({
      type: 'tools/changeTable',
      payload: {
        [`meter${item}`]: [], meterArr, meterActiveKey,
        [`pressure-${item}`]:'',
        [`position-${item}`]:'',
      },
    });
  };
  getOption = () => {
    let {
      dispatch, tools: {x,y,trendY,cc},
    } = this.props
    if(trendY.length===0){
      return {}
    }
    let data=[]

    let data2=[]
    for(let i=0;i<x.length;i++){
      console.log('terms[i]',trendY[i])
      data.push([x[i],y[i]])
      data2.push([x[i],trendY[i]])
    }
    let option  = {
      xAxis: {
        name:'压力(Kpa)',
        min:x[0],
        max:x[x.length-1]
      },
      yAxis: {
        name:'位置',
        min:min(y),
        max:max(y)
      },
      tooltip: {
        trigger: 'axis',
      },
      grid:{
        top:'10%'
      },
      legend: {
        data: ['输入线','趋势线'],
        top:'5%'
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      toolbox: {
        show: true,
        emphasis: {
          iconStyle: {
            color: "rgb(255,255,255)"
          }
        },
        feature: {
          dataView: {readOnly: true},
        }
      },
      series: [
        {
          name:'输入线',
          symbolSize: 10,
          data:data,
          type: 'line',
          smooth:true,
        },
        {
          name:'趋势线',
          symbolSize: 10,
          data:data2,
          type: 'line',
          smooth:true,
        }
      ]
    };;
    return option;
  };

  changeDegree = (value) => {
    console.log('value', value);
    let {
      dispatch,
    } = this.props;
    dispatch({
      type: 'tools/changeTable',
      payload: {
        degree: Number(value)
      },
    });
  };

  componentDidMount() {
    let {
      dispatch, tools: {meterArr, meterActiveKey, uuid},
    } = this.props;
    window.addEventListener('resize', this.resize);
    console.log('meterArr', meterArr)
// table.addEventListener('scroll', debounce(this.scroll, 150));
  }


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  render() {
    const that = this;
    let {
      dispatch, tools: {meterArr, trendY, terms, degree,cc,r,p0,p1,p2,p3},
    } = this.props
    const {getFieldDecorator} = this.props.form;
    const meterForms = meterArr.map((item, index) => {
      return (
        <Form style={{display: 'flex'}} className={`custom-table-form custom-table-form${index}`} key={index}
              layout="inline">
          <div style={{width: '70px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9'}}>
            {index + 1}
          </div>
          <FormItem
            style={{flex: '1', marginRight: '0'}}
          >
            {getFieldDecorator(`pressure-${item}`, {
              initialValue: this.props.tools[`pressure-${item}`],
            })(
              <Input className={'meter_number'} allowClear={true}
                     onChange={(e) => {
                       dispatch({
                         type: 'tools/changeTable',
                         payload: {
                           [`pressure-${item}`]: e.target.value
                         },
                       });
                     }}
                     style={{width: '160px'}}/>
            )}
          </FormItem>
          <FormItem
            style={{flex: '1', marginRight: '0'}}

          >
            {getFieldDecorator(`position-${item}`, {
              initialValue: this.props.tools[`position-${item}`],
            })(
              <Input className={'meter_value'} allowClear={true}
                     onChange={(e) => {
                       dispatch({
                         type: 'tools/changeTable',
                         payload: {
                           [`position-${item}`]: e.target.value
                         },
                       });
                     }}
                     style={{width: '160px', fontWeight: 'bold'}}/>,
            )}
          </FormItem>

          <div style={{width: '70px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9'}}>
            <div
              style={{padding: '0 4px', color: '#fff', cursor: 'pointer', background: '#dc0000'}}
              onClick={(e) => {
                this.deleteMeter(item);
              }
              }
            >删除
            </div>
          </div>


        </Form>
      );
    });

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>工具</span>
      </div>
      <div className="table-page" style={{padding: '12px', display: 'flex'}}>
        <div style={{border: '1px solid #d9d9d9', width: 452}}>
          <div style={{lineHeight:1.5,fontSize:'24px',paddingLeft:5,marginBottom:5}}>
          {/*   <div style={{wordBreak: 'break-all'}}>多项式系数:{terms.join('，')}</div>
            <div style={{wordBreak: 'break-all'}}>趋势线:{trendY.join('，')}</div>
            <div style={{wordBreak: 'break-all'}}>cc:{cc}</div>
            <div style={{wordBreak: 'break-all'}}>r:{r}</div> */}
            <div style={{wordBreak: 'break-all'}}>P3 : {terms[0]}</div>
            <div style={{wordBreak: 'break-all'}}>P2 : {terms[1]}</div>
            <div style={{wordBreak: 'break-all'}}>P1 : {terms[2]}</div>
            <div style={{wordBreak: 'break-all'}}>P0 : {terms[3]}</div>
          </div>
          <div style={{
            display: 'flex',
            fontWeight: 'bold',
            lineHeight: '32px',
            height: '32px',
            background: 'rgb(249,249,249)',
          }}>
            <div style={{width: '65px', paddingLeft: '10px', border: '1px solid #d9d9d9'}}>序号</div>
            <div style={{flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9'}}>压力(Mpa)</div>
            <div style={{flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9'}}>位置</div>
            <div style={{width: '65px', paddingLeft: '10px', border: '1px solid #d9d9d9'}}>操作</div>
          </div>
          {meterForms}
          <div style={{display: 'flex'}}>
            <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加行</Button>
            <Button type={'danger'} icon={'delete'} block onClick={this.clearTable}>清空</Button>
          </div>
          <div>
            <Form>
              <FormItem
                style={{marginBottom: "0"}}
                label={'阶数'}

              >
                {getFieldDecorator(`degree`, {
                  initialValue: degree,
                  rules: [{required: true, message: "阶数不能为空"}],
                })(
                  <Select style={{width: '100%'}} onChange={this.changeDegree}>
                    <Option value={2}>2阶</Option>
                    <Option value={3}>3阶</Option>
                  </Select>
                )}
              </FormItem>
            </Form>
          </div>

          <Button type={'primary'} className={'btn-cyan'} icon={'rise'} style={{marginTop: '10px'}} block
                  onClick={this.complete}>计算</Button>

        </div>
        <div style={{flex: 1, background: '#ccc',position:'relative'}}>

          <ReactEcharts
            option={this.getOption()}
            style={{height: '100%', width: '100%'}}
            theme='my_theme'
            //onChartReady={this.onChartReadyCallback}
            //onEvents={EventsDict}
          />
          <div style={{color:'#40a9ff',position:'absolute',left:15,top:5,fontSize:'24px'}}>
            {`R : ${cc}`}
          </div>
        </div>

      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`${this.state.nowDate} 事务`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        okButtonProps={{loading: this.state.btnLoading}}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({editModal: false, editRecord: {}});
        }}

      >
        <AddOrEditPrice
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
